package cn.edu.zzuli.message.chat.web;



import cn.edu.zzuli.message.config.ChatCustomEncoding;
import cn.edu.zzuli.model.dto.ChatMessage;
import cn.edu.zzuli.model.vo.wx.SendMessage;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;



@ServerEndpoint(value ="/websocket/chat/{user}", encoders = ChatCustomEncoding.class)
@Component
@Slf4j
public class WebChat {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，存放每个客户端对应的MyWebSocket对象
    private static ConcurrentHashMap<String, WebChat> webSocketSet = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //当前发消息的人员编号
    private String user = "";


    private static RabbitTemplate rabbitTemplate;
    @Autowired
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate){
        //通过静态注入
        WebChat.rabbitTemplate = rabbitTemplate;
    }


    /**
     * 连接建立成功调用的方法
     * @param session 可选参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(@PathParam(value = "user") String param, Session session, EndpointConfig config) {
        user = param;//接收到发送消息的人员编号
        System.out.println("user:" + user);
        if(webSocketSet.get(param) != null){
            return;
        }

        System.out.println("初次访问");
        this.session = session;
        webSocketSet.put(param, this);//加入map中
        addOnlineCount();
        System.out.println(user + "用户进入聊天");
        System.out.println("当前在线人数" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketSet.get(user) == null){
            return;
        }
        if (!user.equals("") &&webSocketSet.get(user) != null) {
            webSocketSet.remove(user); //从set中删除
            subOnlineCount();//在线减1
            System.out.println(user + "用户退出,当前在线人数为" + getOnlineCount());
        }
    }

    /**
     * 收到客户端消息后调用
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println(message);
        System.out.println(message);
        //获取信息
        ChatMessage chatMessage = JSON.parseObject(message, ChatMessage.class);
        String toUser = chatMessage.getToName();
        String msg = chatMessage.getMessage();
        System.out.println(toUser);
        //发送信息
        SendMessage sendMessage = new SendMessage();
        System.out.println(user);
        sendMessage.setFromName(user);
        sendMessage.setMessage(msg);
        System.out.println(sendMessage);
        //发送给指定用户
        try {
            log.info("发送");
            if(webSocketSet.get(toUser) != null){
            webSocketSet.get(toUser).session.getBasicRemote().sendObject(sendMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (EncodeException e) {
            e.printStackTrace();
        }
    }



    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("错误");
        error.printStackTrace();
    }


    public static synchronized int getOnlineCount() {
        //在线人数
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        //增加
        WebChat.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        //减少
        WebChat.onlineCount--;
    }


}